package com.alliky.home.ui.viewmodel;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.annotation.NonNull;

import com.alliky.core.base.viewmodel.ToolbarViewModel;
import com.alliky.core.bus.RxMessager;
import com.alliky.core.bus.SingleLiveEvent;
import com.alliky.core.data.DataRepository;
import com.alliky.core.entity.BannerEntity;
import com.alliky.core.entity.vo.BannerEntityInfo;
import com.alliky.core.entity.vo.CategoryVO;
import com.alliky.core.entity.vo.GoodsVO;
import com.alliky.core.global.Global;
import com.alliky.core.net.IDisposableObserver;
import com.alliky.core.util.KLog;
import com.alliky.core.util.RxToast;
import com.alliky.core.util.RxUtils;
import com.alliky.home.ui.activity.HomeGoodsDetailsActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

/**
 * @Description TODO
 * @Author wxianing
 * @Date 2020-11-15
 */
public class HomeViewModel extends ToolbarViewModel<DataRepository> {

    public final static String KEY_CLICK_ITEM = "key_click_item";

    public SingleLiveEvent<List<BannerEntity>> bannerEntityList = new SingleLiveEvent<>();

    //监听数据源
    public SingleLiveEvent<List<BannerEntityInfo>> bannerEntity = new SingleLiveEvent<>();
    public SingleLiveEvent<List<CategoryVO>> getCategoryDataEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<List<GoodsVO>> getHotGoodsEvent = new SingleLiveEvent<>();

    //下拉刷新完成
    public SingleLiveEvent finishRefresh = new SingleLiveEvent<>();
    //上拉加载完成
    public SingleLiveEvent finishLoadMore = new SingleLiveEvent<>();

    private int pageNum = 1;
    private int pageSize = 12;

    public HomeViewModel(@NonNull Application application) {
        super(application);
        RxMessager.getDefault().register(HomeViewModel.this, KEY_CLICK_ITEM, GoodsVO.class, goodsVO -> {
            RxToast.success(goodsVO.getGoods_name());

            Bundle bundle = new Bundle();
            bundle.putString(Global.KEY.USERNAME, "点击按钮");

//            startActivity(HomeGoodsDetailsActivity.class, bundle);
            registerForActivityResult(HomeGoodsDetailsActivity.class, new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK) {
                        String title = result.getData().getStringExtra(Global.KEY.TITLE);
                        KLog.d("title", "   >>>>>>:  " + title);
                    }
                }
            });
        });
        initToolbar();
    }

    public void initToolbar() {
        setBackIconVisible(View.GONE);
        setTitleText("首页");
    }

    public void getCategoryData() {
        WeakHashMap param = new WeakHashMap();
        param.put("1", 1);
        mRepository.getCategory(param)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))// 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())// 线程调度
                .compose(RxUtils.exceptionTransformer())// 网络错误的异常转换
                .doOnSubscribe(this)
                .subscribe(new IDisposableObserver<List<CategoryVO>>(this) {
                    @Override
                    protected void onResult(List<CategoryVO> categoryVOS) {
                        getCategoryDataEvent.postValue(categoryVOS);
                    }
                });
    }

    public void getBannerData() {
        //可以调用addSubscribe()添加Disposable，请求与View周期同步
        WeakHashMap<String, Object> param = new WeakHashMap<>();
        param.put("type", 1);
        mRepository.getBanner(param)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))// 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())// 线程调度
                .compose(RxUtils.exceptionTransformer())// 网络错误的异常转换
                .doOnSubscribe(this)
                .subscribe(new IDisposableObserver<List<BannerEntity>>(this) {
                    @Override
                    protected void onResult(List<BannerEntity> bannerEntities) {
                        bannerEntityList.postValue(bannerEntities);
                        List<BannerEntityInfo> infoList = new ArrayList<>();
                        for (int i = 0; i < bannerEntities.size(); i++) {
                            BannerEntity entity = bannerEntities.get(i);
                            BannerEntityInfo info = new BannerEntityInfo();
                            info.setBannerEntity(entity);
                            infoList.add(info);
                        }
                        bannerEntity.postValue(infoList);
                    }
                });
    }

    public void getHotGoods(boolean isRefresh) {
        pageNum = isRefresh ? 1 : pageNum;
        WeakHashMap param = new WeakHashMap<>();
        param.put("pageNum", pageNum);
        param.put("pageSize", pageSize);
//        param.put("keyword", "");
        mRepository.getHotGoods(param)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))// 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())// 线程调度
                .compose(RxUtils.exceptionTransformer())// 网络错误的异常转换
                .doOnSubscribe(this)
                .subscribe(new IDisposableObserver<List<GoodsVO>>() {
                    @Override
                    protected void onResult(List<GoodsVO> goodsVOS) {
                        if (isRefresh) {
                            finishRefresh.call();
                        } else {
                            finishLoadMore.call();
                        }
                        pageNum += 1;
                        getHotGoodsEvent.postValue(goodsVOS);
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (isRefresh) {
                            finishRefresh.call();
                        } else {
                            finishLoadMore.call();
                        }
                        super.onError(e);
                    }
                });
    }
}
